package com.hirsi.common.core.validator;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.lang.Validator;
import com.hirsi.common.core.validator.annotation.Birthday;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDate;

/**
 * 生日验证实现
 * @author 封夕
 * @since 2023/6/7 17:28
 */
public class BirthdayValidator implements ConstraintValidator<Birthday, LocalDate> {

    private boolean ignoreNull;

    @Override
    public void initialize(Birthday constraintAnnotation) {
        this.ignoreNull = constraintAnnotation.ignoreNull();
    }

    @Override
    public boolean isValid(LocalDate s, ConstraintValidatorContext constraintValidatorContext) {
        if (s == null && ignoreNull) return true;
        try {
            String format = LocalDateTimeUtil.format(s, "yyyy-MM-dd");
            return Validator.isBirthday(format);
        } catch (Exception e) {
            return false;
        }
    }
}
